<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #canvas {
            margin: 50px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
</body>
<script>
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    /** @type{HTMLCanvasElement} */
    let canvas = document.getElementById('canvas')
    let screenPoint = canvas.getBoundingClientRect()
    let canDraw = false
    console.log(screenPoint)
    canvas.width = 1024
    canvas.height = 728
    let ctx = canvas.getContext('2d')
    let img = new Image()
    let scaleX,scaleY
    img.src = './代码.jpg'

    img.onload = function () {
        scaleX = img.width / canvas.width
        scaleY = img.height / canvas.height
        console.log(scaleX)
        ctx.drawImage(img, 0, 0, 1024, 728)
        // ctx.drawImage(img, 0, 0, img.width, img.height)
        drawWater(ctx)
    }

    canvas.addEventListener('mousedown', () => {
        canDraw = true
    })
    canvas.addEventListener('mousemove', throttle((event) => {
        if (canDraw) {
            let x = event.pageX - screenPoint.left
            let y = event.pageY - screenPoint.top
            drawScale(ctx, x, y)
        }
    }, 50))
    canvas.addEventListener('mouseup', () => {
        canDraw = false
        ctx.clearRect(0, 0, 1024, 728)
        ctx.drawImage(img, 0, 0, 1024, 728)
        drawWater(ctx)
    })
    /**
     *@param {CanvasRenderingContext2D} ctx
     */
    function drawScale(ctx, x, y) {
        ctx.clearRect(0, 0, 1024, 728)
        ctx.drawImage(img, 0, 0, 1024, 728)

        let offscreen = new OffscreenCanvas(200, 200)
        let ctx2 = offscreen.getContext('2d')
        ctx2.strokeStyle = 'green'
        ctx2.beginPath()
        ctx2.arc(100, 100, 100, 0, 2 * Math.PI)
        ctx2.stroke()
        ctx2.clip()
        ctx2.drawImage(img, x * scaleX, y * scaleY, 200, 200, 0, 0, 200, 200)
        ctx.drawImage(offscreen, x - 100, y - 100)
        drawWater(ctx)
    }
    function drawWater(ctx) {
        ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
        ctx.font = "48px serif";
        ctx.fillText('www.ludun.com', 650, 700)
    }

    function throttle(func, time) {
        let timeout = 0
        return function () {
            let ctx = this, args = arguments
            if (!timeout) {
                timeout = setTimeout(() => {
                    func.apply(ctx, args)
                    timeout = 0
                }, time)
            }
        }
    }
</script>

</html>